<?php
use Illuminate\Support\Facades\Redis;
function wxresp($code,$post = ''){
	$data = array('code'=>$code);
	if ($post && is_string($post)) $data['msg'] = $post;
	elseif ($post) $data = array_merge($data,$post);
	die(json_encode($data));
}

function redisTimeLimit($mid,$sec = 3){
    if (Redis::get('redis_op_limit'.$mid) == 1){
        wxresp(-1,'请勿频繁操作！');
    }
    Redis::setex('redis_op_limit'.$mid,$sec,1);
}

function http_curl($url,$data='',$header='') {
	$curl = curl_init();
	curl_setopt($curl,CURLOPT_TIMEOUT,5000);
	if ($data){
		curl_setopt($curl, CURLOPT_POST, TRUE);
		curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
	}
	curl_setopt($curl, CURLOPT_HEADER, false);
	if ($header){
		$headers = array();
		foreach ($header as $opt => $value) {
			if (strexists($opt, 'CURLOPT_')) {
				curl_setopt($curl, constant($opt), $value);
			} elseif (is_numeric($opt)) {
				curl_setopt($curl, $opt, $value);
			} else {
				$headers[] = "{$opt}: {$value}";
			}
		}
		if (!empty($headers)) {
			curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		}
	}
	curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
	curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
	curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
	curl_setopt($curl,CURLOPT_URL,$url);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
	$res = curl_exec($curl);
	if($res){
		$contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
		curl_close($curl);
		return array('contentType'=>$contentType,'content'=>$res);
	}else {
		$errno = curl_errno($curl);
		$error = curl_error($curl);
		curl_close($curl);
		return array('content'=>error(-1, "错误码： {$errno} 错误信息：".$error));
	}
}

function checkcaptcha2($code) {
	global $_GPC;
	$codehash = md5(strtolower($code) . 'junkm');
	if ( $codehash == $_SESSION['__code']) {
		$return = true;
	} else {
		$return = false;
	}
	$_SESSION['__code'] = '';
	isetcookie('__code', '');
	return $return;
}

function array2xml($arr, $level = 1) {
    $s = $level == 1 ? "<xml>" : '';
    foreach ($arr as $tagname => $value) {
        if (is_numeric($tagname)) {
            $tagname = $value['TagName'];
            unset($value['TagName']);
        }
        if (!is_array($value)) {
            $s .= "<{$tagname}>" . (!is_numeric($value) ? '<![CDATA[' : '') . $value . (!is_numeric($value) ? ']]>' : '') . "</{$tagname}>";
        } else {
            $s .= "<{$tagname}>" . array2xml($value, $level + 1) . "</{$tagname}>";
        }
    }
    $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
    return $level == 1 ? $s . "</xml>" : $s;
}

function ToXml($data)
{
	$xml = '';
	foreach ($data as $key => $val) {
		if($key==="ExtendInfo"){
			$xml    .=  "<$key key='callbackPage'>";
		}else if(is_numeric($key)){
			$xml    .=  "";
		}else{
			$xml    .=  "<$key>";
		}
		$xml    .=  ( is_array($val) || is_object($val)) ? ToXml($val) : $val;
		list($key, ) = explode(' ', $key);

		//去数字的<1></1>
		if(is_numeric($key)){
			$xml    .=  "";
		}else{
			$xml    .=  "</$key>";
		}

	}
	return $xml;
}

function ToUrlParams($post)
{
	$buff = "";
	foreach ($post as $k => $v)
	{
		if($k != "sign" && $v != "" && !is_array($v)){
			$buff .= $k . "=" . $v . "&";
		}
	}
	$buff = trim($buff, "&");
	return $buff;
}

function curPost($url,$post_data = '',$notjson = false) {
	$curl = curl_init();
	//设置抓取的url
	curl_setopt($curl, CURLOPT_URL, $url);
	//设置头文件的信息作为数据流输出
	curl_setopt($curl, CURLOPT_HEADER, 0);

	//设置获取的信息以文件流的形式返回，而不是直接输出。
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	if ($post_data){
		//设置post方式提交
		curl_setopt($curl, CURLOPT_POST, 1);
		//设置post数据
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
	}
	//执行命令
	$data = curl_exec($curl);
	//关闭URL请求
	curl_close($curl);
	if ($notjson) return $data;
	return json_decode($data,true);
}

function random($length, $numeric = FALSE) {
	$seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
	if ($numeric) {
		$hash = '';
	} else {
		$hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
		$length--;
	}
	$max = strlen($seed) - 1;
	for ($i = 0; $i < $length; $i++) {
		$hash .= $seed[mt_rand(0, $max)];
	}
	return $hash;
}

function getip() {
	static $ip = '';
	$ip = $_SERVER['REMOTE_ADDR'];
	if(isset($_SERVER['HTTP_CDN_SRC_IP'])) {
		$ip = $_SERVER['HTTP_CDN_SRC_IP'];
	} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
		foreach ($matches[0] AS $xip) {
			if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
				$ip = $xip;
				break;
			}
		}
	}
	return $ip;
}

function uploadImage($img){
	if ($img){
		if (is_array($img)){
			foreach ($img as $k => $i) {
				if (strpos('A'.$i, 'data:image') > 0){
					$image = explode(',',$i);
					$image = $image[1];
					$name = date('YmdHis').random(10,1).".png";
					saveFile($name, base64_decode($image));
					$img[$k] = $name;
				}elseif (strpos('A'.$i, "uploads/") > 0){
					$img[$k] = str_replace("/uploads/", "", $i);
				}
			}
		}elseif (strpos('A'.$img, 'data:image') > 0){
			$image = explode(',',$img);
			$image = $image[1];
			$name = date('YmdHis').random(10,1).".png";
			saveFile($name, base64_decode($image));
			return $name;
		}elseif (strpos('A'.$img, "uploads/") > 0){
			return str_replace("/uploads/", "", $img);
		}
	}
	return $img;
}

function saveFile($name,$filedata){
	file_put_contents(public_path()."/uploads/".$name,$filedata);
}

function getEditorContent($content){
	$content = htmlspecialchars_decode($content);
	if (strpos($content, 'src="/uploads/editor/') > 0){
		$content = str_replace("/uploads/editor/", "//".$_SERVER['HTTP_HOST']."/uploads/editor/", $content);
	}
	return $content;
}

function getImage($names,$fullpath = false){
	if (empty($names)) return $names;
	$host = '';
	if ($fullpath) $host = "http://".$_SERVER['HTTP_HOST'];
	if (is_array($names)){
		foreach ($names as $k => $value) {
			if (strpos('A'.$value, "http") > 0 || strpos('A'.$value, "//") > 0) continue;
			$names[$k] = $host."/uploads/".$value;
		}
		return $names;
	}
	if (strpos('A'.$names, "http") > 0 || strpos('A'.$names, "//") > 0) return $names;
	return $host."/uploads/".$names;
}

function getServerImage($names){
	if (empty($names)) return $names;
	$host = "https://".$_SERVER['HTTP_HOST'];
	if (is_array($names)){
		foreach ($names as $k => $value) {
			$names[$k] = str_replace("/uploads/", '', str_replace($host, '', $value));
		}
		return $names;
	}
	return str_replace("/uploads/", '', str_replace($host, '', $names));
}

function tpl_image($name,$val,$jscallback = '',$onlyupload = false){
	$nname = str_replace("]", "-", str_replace("[", "-", $name));
	$html = "
	<div class='input-group'>
	<input type='text' ".($onlyupload?"readonly":"")." class='form-control' id='{$nname}_inputid' name='{$name}' value='{$val}'>
	<div class='input-group-btn'>
	<button class='btn btn-default' type='button'>上传图片<input type='file' onchange='onTplUploadImg{$jscallback}(this,\"{$nname}\")' accept='image/png,image/jpeg' style='position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;z-index: 3;'></button>
	<button class='btn btn-danger' ".($val?"":"style='display:none;'")." onclick='onTplUploadDel{$jscallback}(this,\"{$nname}\")' type='button'>清除图片</button>
	</div>
	</div>
	<img id='{$nname}_imgshow' style='height: 100px;margin-top: 10px;' src='".getImage($val)."'>
	";
	if (!defined('TPL_IMAGE_SHOW'.$jscallback)) {
		$html .= "
		<script>
		function onTplUploadImg{$jscallback}(obj,name){
		var file = $(obj)[0].files[0];
		if(!file) return;
		var reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = function(e) {
		$('#'+name+'_imgshow').attr('src',this.result)
		$('#'+name+'_inputid').val(this.result);
		$(obj).parent().next().show();
		".($jscallback?"{$jscallback}(obj,this.result)":"")."
	};
	}
	function onTplUploadDel{$jscallback}(obj,name){
	$('#'+name+'_imgshow').attr('src','')
	$('#'+name+'_inputid').val('');
	$(obj).hide();
	".($jscallback?"{$jscallback}(obj)":"")."
		}
	   	</script>
		";
		define('TPL_IMAGE_SHOW'.$jscallback, true);
	}
	echo $html;
}

function tpl_images($name,$imgs){
	$nname = str_replace("]", "-", str_replace("[", "-", $name));
	$html = "
	<ul class='list-inline clearfix lyear-uploads-pic'>
	";
	if ($imgs){
		foreach ($imgs as $i) {
			$html .= "
			<li class='col-xs-4 col-sm-3 col-md-2'>
			<input type='hidden' name='{$name}[]' value='{$i}'/>
			<figure>
			<img src='".getImage($i)."'>
					<figcaption>
	                	<a class='btn btn-round btn-square btn-danger' onclick='$(this).parent().parent().parent().remove();'><i class='mdi mdi-delete'></i></a>
					</figcaption>
				</figure>
			</li>
			";
		}
	}
	$html .= "
        <li class='col-xs-4 col-sm-3 col-md-2'>
        	<a class='pic-add' style='position: relative;min-height: 200px;' id='add-pic-btn' title='点击上传'>
            	<input type='file' multiple='multiple' onchange='onTplUploadImgs(\"{$name}\",this)' accept='image/png,image/jpeg' style='position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;z-index: 3;'>
            </a>
		</li>
    </ul>
	";
	if (!defined('TPL_IMAGES_SHOW')) {
		$html .= "
		<script>
		function onTplUploadImgs(name,obj){
		var files = $(obj)[0].files;
		if(!files) return;
		$.each(files,function(k,v){
			var reader = new FileReader();
			reader.readAsDataURL(v);
			reader.onload = function(e) {
				var str = '<li class=\"col-xs-4 col-sm-3 col-md-2\">';
				str += '<input type=\"hidden\" name=\"'+name+'[]\" value=\"'+this.result+'\">';
				str += '<figure>';
				str += '<img src=\"'+this.result+'\">';
				str += '<figcaption>';
				str += '<a class=\"btn btn-round btn-square btn-danger\" onclick=\"$(this).parent().parent().parent().remove();\"><i class=\"mdi mdi-delete\"></i></a>';
				str += '</figcaption>';
				str += '</figure>';
				str += '</li>';
				$(obj).parent().parent().before(str);
			};
		});
	}
	</script>
	";
		define('TPL_IMAGES_SHOW', true);
	}
	echo $html;
}

function tpl_editor($name,$val){
	$nname = str_replace("]", "-", str_replace("[", "-", $name));
	$html = "
		<div id='{$nname}-editor'></div>
		<textarea id='{$nname}-content' style='display: none;' name='{$name}'>{$val}</textarea>
		";
		if (!defined('TPL_EDITOR_SHOW')) {
			$html .= "
				<script src='/static/js/wangEditor.min.js'></script>
			";
			define('TPL_EDITOR_SHOW', true);
		}
		$html .= "
		<script>
			var editor = new window.wangEditor('#{$nname}-editor')
			editor.config.showFullScreen = false
			editor.config.uploadFileName  = 'file'
			editor.config.uploadImgServer = '/Admin/editorUpload';
			editor.config.onchange = function(html){
				$('#{$nname}-content').val(html)
			}
			editor.create()
			".($val ? "editor.txt.html('{$val}')" : "")."
		</script>
		";
	echo $html;
}
function error($code, $msg){
	return array('errno' => $code, 'msg' => $msg);
}
function is_error($result){
	if(is_array($result) && isset($result['errno']) && $result['errno']!=0){
		return true;
	}
	return false;
}
function getRand($proArr){
	$result = '';
	$proSum = array_sum($proArr);

	foreach ($proArr as $key => $proCur ) {
		$randNum = mt_rand(1, $proSum);

		if ($randNum <= $proCur) {
			$result = $key;
			break;
		}
		$proSum -= $proCur;
	}

	unset($proArr);
	return $result;
}